from flask import Flask, render_template, request, jsonify, Response,send_file
import os
from xunfeitext2wav import text2wav
# 解除注释使用讯飞语音识别
# from xunfei_wav2str import w2s
from localw2s import w2s
from kimi_http import chat_main, messages_queue

UPLOAD_FOLDER = 'uploads'  # 设置上传文件保存路径,没有则创建
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)
app = Flask(__name__)
audio_path_none= "reponse_audio/none_recvive.wav"


def generate_wav_stream(audio_path):
    """流式读取本地 WAV 文件并返回响应"""
    with open(audio_path, 'rb') as f:
        while chunk := f.read(1024):  # 每次读取 1024 字节
            yield chunk  # 使用 yield 来逐块返回数据


# 处理文件上传的 POST 请求
@app.route('/', methods=['POST', 'GET'])
def upload_chunk():
    if request.method == 'POST':
        # 获取文件块和完成标志位
        file_chunk = request.files.get('file_chunk')
        is_last = int(request.form.get('is_last'))
        file_name = request.form.get('file_name')
        # 生成保存文件的路径
        file_path = os.path.join(UPLOAD_FOLDER, file_name)
        # 追加写入文件块
        with open(file_path, 'ab') as f:
            f.write(file_chunk.read())
        # 根据是否为最后一个块，返回不同的响应
        if is_last == 1:
            # 语音识别
            text = w2s(file_path)
            if text is None or text == '':
                # 提示音频文件路径
                # 返回音频文件流
                return send_file(audio_path_none, mimetype='audio/wav')
            # 调用kimi_api接口
            reply = chat_main(text)
            text2wav(reply, f'./download/{file_name}.pcm',f'./download/{file_name}')
            return send_file(f'./download/{file_name}', mimetype='audio/wav'), 200
            # 删除上传的文件
            # os.remove(file_path)
            # return Response(reply, content_type='text/plain;charset=utf-8'), 200
            # return Response("语音识别成功，正在处理。"), 200
        else:
            # 返回空响应，状态码为 204
            return jsonify({'status': 'reading'}), 204
    else:

        # 如果是 GET 请求，显示上传表单网页ui
        # return send_file(audio_path_none, mimetype='audio/wav'), 200
        return render_template('index.html')


if __name__ == '__main__':
    app.run("0.0.0.0", debug=True, port=8052)
